package com.xin.service.impl;

import com.xin.config.JwtUtil;
import com.xin.config.RedisCache;
import com.xin.config.UserInfo;
import com.xin.entity.LoginUser;
import com.xin.entity.UserAccountEntity;
import com.xin.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private AuthenticationManager  authenticationManager;


    @Override
    public Map<String,Object> userLogin(UserAccountEntity userAccountEntity) {
        com.xin.entity.UserInfo userInfo = new com.xin.entity.UserInfo();
        userInfo.setUsername(userAccountEntity.getUserAccount());
        userInfo.setPassword(userAccountEntity.getUserPassword());
        System.out.println("LoginServiceImpl");
        //通过通过UsernamePasswordAuthenticationToken获取用户名和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userInfo.getUsername(), userInfo.getPassword());

        //委派机制对authenticationToken 进行用户认证
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)){
            System.out.println("登录失败");
            throw new RuntimeException("登录失败");
        }
        Object principal = authenticate.getPrincipal();
        LoginUser loginUser = (LoginUser) principal;

        UserInfo.userInfo.put("userInfo",loginUser);
        System.out.println("读取userInfo\t"+loginUser);
        Map<String,Object> map = new HashMap<>();
        map.put(loginUser.getUserInfo().getUsername(), JwtUtil.createJWT(loginUser.getUsername().toString()));

        return map;
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public boolean loginOut() {
        //从SecurityContextHolder中的userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken authentication1 = (UsernamePasswordAuthenticationToken) authentication;

        LoginUser  principal = (LoginUser) authentication1.getPrincipal();

        System.out.println("读取出来的数据\t"+principal.toString());
        return true;
    }
}
